/*
  ******************************************************************************
  * @file    i2c_demo.c
  * @author  FreqChip Firmware Team
  * @version V1.0.0
  * @date    2021
  * @brief   I2C module Demo.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2021 FreqChip.
  * All rights reserved.
  ******************************************************************************
*/
#include "i2c_demo.h"

#include "driver_gpio.h"
#include "driver_i2c.h"
#include "driver_system.h"

#include "co_printf.h"
#include "co_log.h"

#include "ble_stack.h"


GPIO_InitTypeDef   GPIO_Handle;
I2C_HandleTypeDef  I2C1_Handle;

uint8_t TxBufferI2C[256];
uint8_t RxBufferI2C[256];

/************************************************************************************
 * @fn      i2c_demo
 *
 * @brief   i2c demo

 */
void i2c_demo(void)
{
	uint32_t i;
	
    __SYSTEM_GPIO_CLK_ENABLE();
	__SYSTEM_I2C1_CLK_ENABLE();
	
	/* I2C IO Init */
    GPIO_Handle.Pin       = GPIO_PIN_2 | GPIO_PIN_3;
    GPIO_Handle.Mode      = GPIO_MODE_AF_PP;
    GPIO_Handle.Pull      = GPIO_PULLUP;
    GPIO_Handle.Alternate = GPIO_FUNCTION_1;
    gpio_init(GPIO_A, &GPIO_Handle);

	/* I2C Init */
    I2C1_Handle.I2Cx = I2C1;
    I2C1_Handle.Init.I2C_Mode = I2C_MODE_MASTER_7BIT;
    I2C1_Handle.Init.SCL_HCNT = 500;
    I2C1_Handle.Init.SCL_LCNT = 500;
    i2c_init(&I2C1_Handle);
	
	for(i = 0; i < 256; i++)
	{
		TxBufferI2C[i] = i;
	}
	
    /* write EEPROM  */
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*0, &TxBufferI2C[32*0], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*1, &TxBufferI2C[32*1], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*2, &TxBufferI2C[32*2], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*3, &TxBufferI2C[32*3], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*4, &TxBufferI2C[32*4], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*5, &TxBufferI2C[32*5], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*6, &TxBufferI2C[32*6], 32);
    i2c_memory_write(&I2C1_Handle, 0xA0, 32*7, &TxBufferI2C[32*7], 32);
    
	/* read EEPROM */
    i2c_memory_read(&I2C1_Handle, 0xA0, 0, RxBufferI2C, 256);
    
    for (i = 0; i < 256; i++)
    {
		if (RxBufferI2C[i] != TxBufferI2C[i])
		{
			co_printf("I2C write EEPROM Error \r\n");
		}
    }
	
	co_printf("I2C EEPROM Demo end \r\n");
	
	while(1);
}

